#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <time.h>

#include "itoa.h"
#include "logger.h"

void Log(int level, char *message, char *vdaName, int PID, int TID)
{
  FILE *log = fopen("./fuselage.log","a");
  char *toWrite = (char *)malloc(BUFSIZ);

  time_t  currtime;
  char charTime[10] = {0};

  time(&currtime);
  strftime(charTime,sizeof(charTime)-1,"%D %T",localtime(&currtime));

  strcpy(toWrite, charTime);

  strcat(toWrite," ");

  strcat(toWrite, "FUSELAGE ");

  char *pid = (char *)malloc(32);
  pid = itoa(PID,10);
  strcat(toWrite, pid);
  free(pid);

  char *tid = (char *)malloc(32);
  tid = itoa(TID,10);
  strcat(toWrite, tid);
  free(tid);

  char *lev = (char *)malloc(32);
  switch(level)
  {
    case 0:
      strcpy(lev,"DEBUG ");
      break;
    case 1:
      strcpy(lev,"ERROR ");
      break;
    case 2:
      strcpy(lev,"FATAL ");
      break;
  }
  strcat(toWrite,lev);
  free(lev);

  strcat(toWrite,message);

  strcat(toWrite,"\n\0");

  fwrite(toWrite,strlen(toWrite),0,log);

  free(toWrite);
  fclose(log);
  return;
}
